package com.tramp.basic.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.tramp.basic.dao.AdminDao;
import com.tramp.basic.entity.Admin;
import com.tramp.basic.entity.AdminRole;
import com.tramp.basic.vo.AdminVO;
import com.tramp.frame.server.base.BaseService;
import com.tramp.frame.server.base.dao.AdminBaseDao;
import com.tramp.frame.server.base.field.AdminField;
import com.tramp.frame.server.exception.GenericException;
import com.tramp.utils.MD5Utils;

/**
* 管理人员业务逻辑层
* @author liulanghan
* @since 2017-11-04 17:42:44
*/
@Service
@Transactional
public class AdminService extends BaseService<Admin> {

	@Autowired
	private AdminDao adminDao;

	@Autowired
	private RoleService roleService;
	@Autowired
	private AdminRoleService adminRoleService;

	public AdminService(AdminBaseDao adminDao) {
		super(adminDao);
	}

	public List<Admin> getList() {
		return adminDao.getList();
	}

	public Admin login(String username, String password) {
		return adminDao.login(username, password);
	}

	public void saveAdmin(AdminVO adminVO) {
		Admin admin = new Admin();
		BeanUtils.copyProperties(adminVO, admin);
		admin.setPassword(MD5Utils.encrypt(admin.getPassword()));
		if (StringUtils.isNotBlank(admin.getId())) {
			this.updateField(admin, AdminField.update().name().mobile().remark().status());
		}
		else {
			//判断用户名是否已经存在
			Admin adminDb = adminDao.getByUserName(admin.getUsername());
			if (adminDb != null) {
				throw new GenericException("用户名已存在,请更换");
			}
			this.insert(admin);
			//删除原有角色
			roleService.deleteAdminRole(admin.getId());
		}
		List<String> roleIdList = adminVO.getRoleIdList();
		String adminId = admin.getId();
		//保存角色
		List<AdminRole> adminRoles = Lists.newArrayList();
		for (String roleId : roleIdList) {
			AdminRole adminRole = new AdminRole();
			adminRole.setAdminId(adminId);
			adminRole.setRoleId(roleId);
			adminRoles.add(adminRole);
		}
		adminRoleService.insert(adminRoles);
	}

	public void deleteAdmin(String id) {
		this.delete(id);
		//删除角色权限
		roleService.deleteAdminRole(id);
	}
}
